﻿using System.Collections.Generic;
using System.Linq;
using Socium.Domain.Collections;
using Socium.Domain.Documents;
using Socium.Presentation;

namespace Socium.Documents.Sociograms {
	class SociogramViewModel : PageViewModel {
		//readonly Document _document;
		//readonly Sociogram _sociogram;

		readonly ICollection<NodeViewModel> _nodes = new LinkedList<NodeViewModel>();
		readonly ICollection<RelationGroupViewModel> _criterias = new LinkedList<RelationGroupViewModel>();
		readonly ICollection<RelationViewModel> _relations = new LinkedList<RelationViewModel>();

		public SociogramViewModel(Document document, Sociogram sociogram) : base(sociogram.Name) {
			//_document = document;
			//_sociogram = sociogram;

			DisplayName = sociogram.Name;

			_nodes.AddRange(sociogram.Nodes.MapLazy(node => new NodeViewModel(node)));
			_criterias.AddRange(document.Criterias.MapLazy(criteria => new RelationGroupViewModel(criteria)));

			var criterias = _criterias.MakeDictionary(view_model => view_model.RelationGroup);
			_nodes.Iterate(view_model => AddCounters(view_model, document, sociogram, criterias));

			var nodes = _nodes.MakeDictionary(view_model => view_model.Node);
			_relations.AddRange(sociogram.GetRelations(document).MapLazy(relation => CreateRelationViewModel(relation, nodes, criterias)));
		}

		static void AddCounters(NodeViewModel view_model, Document document, Sociogram sociogram, IDictionary<RelationGroup, RelationGroupViewModel> criterias) {
			var counter_view_models = 
				from criteria in document.Criterias 
				let counter = sociogram.GetCounter(document, view_model.Node, criteria) 
				where !counter.IsEmpty 
				select new CounterViewModel(criterias[criteria], counter);

			view_model.Counters.AddRange(counter_view_models);
		}

		static RelationViewModel CreateRelationViewModel(SociogramRelation relation, IDictionary<Node, NodeViewModel> nodes, IDictionary<RelationGroup, RelationGroupViewModel> criterias) {
			return new RelationViewModel(relation, criterias[relation.RelationGroup], nodes[relation.From], nodes[relation.To]);
		}

		public ICollection<NodeViewModel> Nodes {
			get { return _nodes; }
		}

		public ICollection<RelationViewModel> Relations {
			get { return _relations; }
		}
	}
}
